package main

import (
	"fmt"
	"io/ioutil"
	"net/http"
	"time"

	"github.com/ovh/cds/sdk"
	"github.com/ovh/cds/sdk/log"
)

func (wk *currentWorker) vulnerabilityHandler(w http.ResponseWriter, r *http.Request) {
	// Get body
	data, errra := ioutil.ReadAll(r.Body)
	if errra != nil {
		log.Error("vulnerabilityHandler> Cannot ReadAll err: %s", errra)
		w.WriteHeader(http.StatusBadRequest)
		return
	}

	uri := fmt.Sprintf("/queue/workflows/%d/vulnerability", wk.currentJob.wJob.ID)

	var lasterr error
	var code int
	for try := 1; try <= 10; try++ {
		log.Info("vulnerabilityHandler> Sending vulnerability report...")
		_, code, lasterr = sdk.Request("POST", uri, data)
		if lasterr == nil && code < 300 {
			log.Info("vulnerabilityHandler> Send vulnerability report OK")
			return
		}
		log.Warning("vulnerabilityHandler> Cannot send vulnerability report: HTTP %d err: %s - try: %d - new try in 5s", code, lasterr, try)
		time.Sleep(5 * time.Second)
	}
	log.Warning("vulnerabilityHandler> unable to send vulnerability result: %d %v", code, lasterr)
	w.WriteHeader(http.StatusBadRequest)
}
